
import request from "./request";
import { getStore } from "./store";
import listToTree from "./utils/listToTree";
import emitter from "./utils/emitter";
import utils from "./utils";

/**
 * 核心功能
 */
class Cloud {
  /**
   * 版本
   * @type {string}
   */
  version = "3.0.11";
  /**
   * Vue当前
   * @type {string}
   */
  vm = "";
  /**
   * 配置文件
   * @type {{AppURL: string}}
   */
  config = {
    AppURL: "http://myhost"
  };

  /**
   *构造方法
   * @param Vue
   * @param Options
   */
  constructor(Vue, Options) {
    this.vm = Vue;
    this.config = Options;
    this.$store = getStore();
  }

  /**
   * 获取地址栏参数
   * @param key
   * @returns {null|string}
   */
  query(key) {
    const url = new URL(window.location.href);

    const questionMarkIndex = url.href.indexOf("?");
    if (questionMarkIndex === -1) {
      return null;
    }
    const queryParams = url.href.substring(questionMarkIndex + 1).split("&");
    for (let i = 0; i < queryParams.length; i++) {
      const paramPair = queryParams[i].split("=");
      if (paramPair[0] === key) {
        return decodeURIComponent(paramPair[1]);
      }
    }
    return null;
  }

  /**
   * 设置前缀
   * @returns {{}}
   */
  prefix() {
    return {};
  }

  /**
   *解析URL地址
   * @param url
   * @returns {string}
   */
  getUrl(url) {
    let AppURL = "";
    if (this.config.AppURL) {
      if (utils.isHttpUrl(url)) {
        AppURL = this.config.AppURL;
      } else if (this.config.AppURL.indexOf("/") === 0) {
        AppURL = "";
      } else {
        AppURL = "";
      }
    }
    if (!utils.isHttpUrl(url)) {
      if (url.indexOf("/") === 0) {
        url = url.slice(1);
      }
      //重置URL地址
      url = `${AppURL}/api/` + url;
    }
    return url;
  }

  /**
   * 数据GET方法
   * @param url
   * @param params
   * @returns {*}
   */
  get(url, params = null) {
    console.log("this.vm", this.query("uniqueId"));
    return request({
      url: this.getUrl(url),
      method: "GET",
      headers: {
        "x-api-type": "web",
        "x-api-uniqueId": this.query("uniqueId") ?? ""
      },
      params: Object.assign(this.prefix(), params)
    });
  }

  /**
   * 创建POST
   * @param url
   * @param params
   * @param data
   * @returns {*}
   */
  post(url, params = null, data = null) {
    //设置数据结构
    if (data === null) {
      data = params;
      params = null;
    }
    return request({
      url: this.getUrl(url),
      method: "POST",
      headers: {
        "x-api-type": "web",
        "x-api-uniqueId": this.query("uniqueId") ?? ""
      },
      params: Object.assign(this.prefix(), params),
      data: data
    });
  }

  /**
   * 创建POST
   * @param url
   * @param method
   * @param data
   * @returns {*}
   */
  http(url, method = "POST", data = null) {
    return request({
      url: this.getUrl(url),
      method: method,
      headers: {
        "x-api-type": "web",
        "x-api-uniqueId": this.query("uniqueId") ?? ""
      },
      data: data
    });
  }

  /**
   * 创建POST
   * @param url
   * @param params
   * @param data
   * @param config
   * @returns {*}
   */
  upload(url, params = null, data = null, config = {}) {
    //设置数据结构
    if (data === null) {
      data = params;
      params = null;
    }
    //判断是否是表单数据
    if (params instanceof FormData) {
      //判断如果data数据存在的情况则赋值给config
      if (data) {
        config = data;
      }
      //没有params传参，直接是文件类
      data = params;
    }
    return request({
      url: this.getUrl(url),
      method: "POST",
      headers: {
        "Content-type": "multipart/form-data",
        "x-api-uniqueId": this.query("uniqueId") ?? "",
        "x-api-type": "web"
      },
      ...config,
      params: Object.assign(this.prefix(), params),
      data: data
    });
  }

  /**
   * 执行用户信息
   * @param url
   * @param params
   * @param data
   * @returns {Promise<unknown>}
   */
  userinfo(url, params = null, data = null) {
    return new Promise((resolve, reject) => {
      this.$store
        .dispatch("userinfo", () => {
          return this.post.apply(this, [url, params, data]);
        })
        .then(data => {
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  /**
   * 执行登录方法
   * @param url
   * @param params
   * @param data
   * @returns {Promise<unknown>}
   */
  login(url, params = null, data = null) {
    return new Promise((resolve, reject) => {
      this.$store
        .dispatch("login", () => {
          return this.post.apply(this, [url, params, data]);
        })
        .then(data => {
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  /**
   * 退出登录
   * @returns {Promise<unknown>}
   */
  logout() {
    return new Promise((resolve, reject) => {
      this.$store
        .dispatch("logout")
        .then(data => {
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  /**
   * 跳转页面
   */
  go(url, query = null) {
    if (Object.prototype.toString.call(url) === "[object Object]") {
      if (url.query) {
        url.query = Object.assign(url.query, query);
      }
    } else {
      url = {
        path: url,
        query
      };
    }
    emitter.emit("routerEvent", url);
  }

  /**
   * 事件监听
   * @param event
   * @param data
   */
  emit(event, data) {
    emitter.emit(event, data);
  }

  /**
   * 事件执行
   * @param event
   * @param fun
   */
  on(event, fun) {
    emitter.on(event, fun);
  }

  /**
   * 判断是否登录
   * @returns {*}
   */
  isLogin() {
    return this.$store.isLogin();
  }

  /**
   * 获取用户信息
   * @returns {*}
   */
  userInfo() {
    return this.$store.userInfo();
  }

  /**
   * 获取路由信息
   * @param value
   * @returns {*}
   */
  routes(value = "") {
    return this.$store.routes(value);
  }

  /**
   * 转json
   * @return {string}       [description]
   * @param value
   */
  toJson(value) {
    return JSON.stringify(value).toString();
  }

  /**
   * json转数组
   * @return {[type]}       [description]
   * @param value
   */
  toArray(value) {
    try {
      return JSON.parse(value);
    } catch (e) {
      return null;
    }
  }

  /**
   * 处理树结构
   * @param options
   * @returns {listToTree}
   */
  toTree(options) {
    return new listToTree(options);
  }
}

/**
 * 插件基础安装
 * @param Vue
 * @param options
 */
const install = function(Vue, options) {
  window.__DEBUG__ = options.debug ?? false;
  Vue.use(VueRouter);
  Vue.prototype.$cloud = new Cloud(Vue, options);
};

const Page = function(obj) {
  return obj;
};

/* istanbul ignore if */
if (typeof window !== "undefined" && !window.$cloud) {
  window.$cloud = new Cloud();
  window.Page = Page;
  window.__DEBUG__ = false;
}

/**
 * 返回CLoud功能列表
 */
export default {
  version: "3.0.0",
  install,
  Page
};
